package com.fourth.controller;

import com.fourth.entity.Cart;
import com.fourth.entity.CartItem;
import com.fourth.entity.Goods;
import com.fourth.service.CartItemService;
import com.fourth.service.CartService;
import com.fourth.service.GoodsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@RestController
public class CartController {


    @Resource
    private CartService cartService;
    @Resource
    private CartItemService cartItemService;
    @Resource
    private GoodsService goodsService;


    /**
     * 首页获取购物车图标数量方法
     * @param request
     * @param response
     * @param session
     * @return
     */
    @GetMapping("/selectCartNum")
    public String selectCartNum(HttpServletRequest request,
                                HttpServletResponse response,
                                HttpSession session){
        setResponseHeader(response);
        //获取登录状态
        Map<String, Object> info = getLoginStateAndInfo(request, response, session);
        Boolean loginState = (Boolean) info.get("loginState");
        Integer uId = (Integer) info.get("uId");
        String uName = (String) info.get("uName");

        if (loginState){
            //已登录：根据sql端的数值
            Integer i = cartService.selectCartNum(uId);


            if (i==null||i==0){
               return String.valueOf(0);
            }

            return String.valueOf(i);

        }else {
            //未登录：根据session的数值
            List<Cart> sessionCart  = (ArrayList<Cart>) session.getAttribute("myCart");

            if (sessionCart==null||0==sessionCart.size()){

                return String.valueOf(0);

            }else{

                int conut=0;
                for (Cart cart : sessionCart) {
                    conut=conut+cart.getNum();
                }


                return String.valueOf(conut);
            }
        }
    }

    /**
     * 购物车页面跳转
     * @param mav
     * @return
     */
    @GetMapping("/goToCart")
    public ModelAndView goToCart(ModelAndView mav){
        mav.setViewName("cart");
        return mav;
    }

    /**
     * 根据登录状态 获取购物车的详情条目
     * @param request
     * @param response
     * @param session
     * @return
     */
    @GetMapping("/getCartItem")
    public List<CartItem> getCartItem(HttpServletRequest request,
                                      HttpServletResponse response,
                                      HttpSession session){
        setResponseHeader(response);

        //获取登录状态
        Map<String, Object> info = getLoginStateAndInfo(request, response, session);
        Boolean loginState = (Boolean) info.get("loginState");
        Integer uId = (Integer) info.get("uId");
        String uName = (String) info.get("uName");

        if (loginState){
            //已登录：显示sql的购物信息
            List<CartItem> carts = cartItemService.selectCartItemByUid(uId);
            return carts;

        }else {
            //未登录：显示session的购物信息
            List<Cart> list = (List<Cart>) session.getAttribute("myCart");

            List<CartItem> carts = new ArrayList<>();

            if (list==null||0==list.size()){
                return null;
            }

            int a = 0;
            for (Cart cart : list) {
                Goods goods = goodsService.selectGoodsById(Integer.valueOf(cart.getGoodId()));
                CartItem cartItem = new CartItem();
                cartItem.setGoodsId(cart.getGoodId());
                cartItem.setId(++a);
                cartItem.setUId(0);
                cartItem.setNum(cart.getNum());
                cartItem.setCreateTime(cart.getCreateTime());
                cartItem.setUpdateTime(cart.getUpdateTime());
                cartItem.setItemId(goods.getItemId());
                cartItem.setTitle(goods.getTitle());

                //购物车单个商品的小计 数据处理
                BigDecimal p = goods.getPrice().multiply(BigDecimal.valueOf(cart.getNum()));
                cartItem.setPrice(p);

                cartItem.setSmallPic(goods.getSmallPic());
                cartItem.setStatus(goods.getStatus());
                cartItem.setStockNum(goods.getStockNum());
                cartItem.setDescription(goods.getDescription());
                carts.add(cartItem);
            }
            return carts;
        }
    }

    @GetMapping("/addGoodNum")
    public Map<String,Object> addGoodNum(HttpServletRequest request,
                                         HttpServletResponse response,
                                         HttpSession session){
        setResponseHeader(response);

        //获取登录状态
        Map<String, Object> info = getLoginStateAndInfo(request, response, session);
        Boolean loginState = (Boolean) info.get("loginState");
        Integer uId = (Integer) info.get("uId");

        //获取请求参数：goodsId
        String goodsId = request.getParameter("goodsId").trim();

        if (loginState){
            //已登录操作:向sql修改数量
            cartService.updateGoodsNum(uId,goodsId);

            //向本地的myCart2修改数据
            List<Cart> carts2 = cartService.selectCartByUid(uId);
            session.setAttribute("myCart2",carts2);

            //返回数据处理
            Map<String,Object> map = new HashMap<>();
            List<Cart> carts = cartService.selectCartByUid(uId);
            int i = 0;
            for (Cart cart : carts) {
                if (goodsId.equals(cart.getGoodId())){
                    i=i+cart.getNum();
                }
            }
            Goods goods = goodsService.selectGoodsById(Integer.valueOf(goodsId));
            BigDecimal p = goods.getPrice().multiply(BigDecimal.valueOf(i));
            if (i>goods.getStockNum()){
                map.put("stockState","no");
            }else {
                map.put("stockState","yes");
            }
            map.put("num",i);
            map.put("subtotal",p);
            return map;

        }else {

            //未登录操作:修改本地session中购物车商品数量
            List<Cart> myCart = (List<Cart>) session.getAttribute("myCart");

            //session购物车 的数据修改 +1
            if (myCart!=null||0<myCart.size()){
                for (Cart cart : myCart) {
                    if (goodsId.equals(cart.getGoodId())){
                        cart.setNum(cart.getNum()+1);
                    }
                }
                session.setAttribute("myCart",myCart);
            }

            //返回数据处理
            Map<String,Object> map = new HashMap<>();
            List<Cart> myCartnum = (List<Cart>) session.getAttribute("myCart");
            int n =0;
            for (Cart cart : myCartnum) {
                if (goodsId.equals(cart.getGoodId())){
                    n=n+cart.getNum();
                }
            }
            Goods goods = goodsService.selectGoodsById(Integer.valueOf(goodsId));
            BigDecimal p = goods.getPrice().multiply(BigDecimal.valueOf(n));

            if (n>goods.getStockNum()){
                map.put("stockState","no");
            }else {
                map.put("stockState","yes");
            }
            map.put("num",n);
            map.put("subtotal",p);
            return map;
        }
    }

    @GetMapping("/cutGoodNum")
    public Map<String,Object> cutGoodNum(HttpServletRequest request,
                                         HttpServletResponse response,
                                         HttpSession session){

        //解决跨域问题
        setResponseHeader(response);

        //获取登录状态
        Map<String, Object> info = getLoginStateAndInfo(request, response, session);
        Boolean loginState = (Boolean) info.get("loginState");
        Integer uId = (Integer) info.get("uId");

        //获取请求参数：goodsId
        String goodsId = request.getParameter("goodsId").trim();
        System.out.println("goodsId:"+goodsId);

        if (loginState){
            //已登录操作:向sql修改数量
            cartService.downdateGoodsNum(uId,goodsId);

            //向本地的myCart2修改数据
            List<Cart> carts2 = cartService.selectCartByUid(uId);
            session.setAttribute("myCart2",carts2);

            //返回数据处理
            Map<String,Object> map = new HashMap<>();
            List<Cart> carts = cartService.selectCartByUid(uId);
            int i = 0;
            for (Cart cart : carts) {
                if (goodsId.equals(cart.getGoodId())){
                    i=i+cart.getNum();
                }
            }
            Goods goods = goodsService.selectGoodsById(Integer.valueOf(goodsId));
            BigDecimal p = goods.getPrice().multiply(BigDecimal.valueOf(i));
            map.put("stockState","yes");
            map.put("num",i);
            map.put("subtotal",p);
            return map;
        }else {

            //未登录操作:修改本地session中购物车商品数量
            List<Cart> myCart = (List<Cart>) session.getAttribute("myCart");

            //session购物车 的数据修改 +1
            if (myCart!=null||0<myCart.size()){
                for (Cart cart : myCart) {
                    if (goodsId.equals(cart.getGoodId())){
                        cart.setNum(cart.getNum()-1);
                    }
                }
                session.setAttribute("myCart",myCart);
            }

            //返回数据处理
            Map<String,Object> map = new HashMap<>();
            List<Cart> myCartnum = (List<Cart>) session.getAttribute("myCart");
            int n =0;
            for (Cart cart : myCartnum) {
                if (goodsId.equals(cart.getGoodId())){
                    n=n+cart.getNum();
                }
            }
            Goods goods = goodsService.selectGoodsById(Integer.valueOf(goodsId));
            BigDecimal p = goods.getPrice().multiply(BigDecimal.valueOf(n));
            map.put("stockState","yes");
            map.put("num",n);
            map.put("subtotal",p);
            return map;
        }
    }

    @GetMapping("/deletCartItem")
    public int deletCartItem(HttpServletRequest request,
                             HttpServletResponse response,
                             HttpSession session){
        setResponseHeader(response);

        //获取登录状态
        Map<String, Object> info = getLoginStateAndInfo(request, response, session);
        Boolean loginState = (Boolean) info.get("loginState");
        Integer uId = (Integer) info.get("uId");

        //获取请求参数：goodsId
        String goodsId = request.getParameter("goodsId").trim();

        if (loginState){
            //已登录操作
            int i = cartService.deletCartItem(uId, goodsId);

            List<Cart> carts2 = cartService.selectCartByUid(uId);
            session.setAttribute("myCart2",carts2);

            return i;
        }else {

            List<Cart> myCart = (List<Cart>) session.getAttribute("myCart");
            if (myCart==null||0==myCart.size()){
                return 0;
            }
            for (int i = 0; i < myCart.size(); i++) {
                if (myCart.get(i).getId()==uId&&myCart.get(i).getGoodId().equals(goodsId)){
                    myCart.remove(i);
                }
            }
            session.setAttribute("myCart",myCart);
            return 1;
        }
    }

    @GetMapping("/getTotalData")
    public Map<String,Object> getTotalData(HttpServletRequest request,
                                           HttpServletResponse response,
                                           HttpSession session){
        setResponseHeader(response);

        //获取登录状态
        Map<String, Object> info = getLoginStateAndInfo(request, response, session);
        Boolean loginState = (Boolean) info.get("loginState");
        Integer uId = (Integer) info.get("uId");

        if (loginState){
            List<CartItem> cartItems = cartItemService.selectCartItemByUid(uId);
            int totalCount = 0;
            BigDecimal totalPrice=BigDecimal.ZERO;
            for (CartItem cartItem : cartItems) {

                Integer num = cartItem.getNum();
                BigDecimal price = cartItem.getPrice().multiply(BigDecimal.valueOf(num));

                totalCount=totalCount+num;
                totalPrice=totalPrice.add(price);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("totalCount",totalCount);
            map.put("totalPrice",totalPrice);
            return map;
        }else{

            List<Cart> myCart = (List<Cart>) session.getAttribute("myCart");

            if (myCart==null||0==myCart.size()){
                int totalCount = 0;
                BigDecimal totalPrice=BigDecimal.ZERO;
                Map<String,Object> map = new HashMap<>();
                map.put("totalCount",totalCount);
                map.put("totalPrice",totalPrice);
                return map;
            }

            int totalCount = 0;
            BigDecimal totalPrice=BigDecimal.ZERO;
            for (Cart cartItem : myCart) {

                Goods goods = goodsService.selectGoodsById(Integer.valueOf(cartItem.getGoodId()));

                Integer num = cartItem.getNum();
                BigDecimal price = goods.getPrice().multiply(BigDecimal.valueOf(num));

                totalCount=totalCount+num;

                totalPrice=totalPrice.add(price);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("totalCount",totalCount);
            map.put("totalPrice",totalPrice);
            return map;
        }

    }


    /**
     * 根据服务端session决定登录状态 提供id和name
     * @param request
     * @param response
     * @param session
     * @return 登录状态 uId uName
     */
    public static Map<String,Object> getLoginStateAndInfo(HttpServletRequest request,
                                                          HttpServletResponse response,
                                                          HttpSession session){
        //获取登录状态
        String uName = (String) session.getAttribute("uName");
        Integer uId = (Integer) session.getAttribute("uId");

        boolean loginState = false;
        if (uName==null||"".equals(uName)||0==uId||uId==null){
            loginState=false;
        }else if (uName!=null||!uName.equals("")){
            loginState=true;
        }

        if(loginState){
            System.out.println("当前登录状态：已登录，用户名="+uName+",ID="+uId);
        }else {
            System.out.println("当前登录状态：未登录，用户名="+uName+",ID="+uId);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("loginState",loginState);
        map.put("uId",uId);
        map.put("uName",uName);
        return map;
    }


    public static void setResponseHeader(HttpServletResponse response){
        //解决跨域问题
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
    }
}
